import { Router } from "https://deno.land/x/oak@v12.6.0/mod.ts";
import { client, closeDB } from "../db.ts";
import { hashPassword, verifyPassword } from "../utils/bcrypt.ts";
import { generateToken } from "./../utils/jwt.ts"; 

const authRouter = new Router();

// 注册路由
authRouter.post("/register", async (ctx) => {

  const { userName, password } = await ctx.request.body().value;

  if (!userName || !password) {
    ctx.response.status = 400;
    ctx.response.body = { message: "Username and password are required" };
    return;
  }

  const hashedPassword = await hashPassword(password);
  const db = await client();

  try {
    console.log(userName)
    const existUser = db.query("SELECT id  from raccoon_user WHERE user_name = ?", [userName]);
    if (existUser.length) {
      ctx.response.status = 404; 
      ctx.response.body = { message: "Username already exists" };
      return;
    }
    console.log(3333)
    console.log(userName,hashedPassword)
    db.query("INSERT INTO raccoon_user (user_name, password) VALUES (?,?)", [userName, hashedPassword]);
    console.log(1111111)
     // 使用 SQL 查询获取最后插入的 ID
     const result = db.query("SELECT LAST_INSERT_ROWID() AS id");
     const lastInsertId = result[0]?.[0];
    ctx.response.status = 200;
    ctx.response.body = { data: { "userName": userName, "userId": lastInsertId} };
  } catch (error) {
    console.error("Error during registration:", error);
    ctx.response.status = 500;
    ctx.response.body = { message: "Internal server error" };
  } finally {
    closeDB(db);
  }

});

// 登录路由
authRouter.post("/login", async (ctx) => {
    const { userName, password } = await ctx.request.body().value;

    if (!userName || !password) {
      ctx.response.status = 400;
      ctx.response.body = { message: "userName and password are required" };
      return;
    }

    const db = await client();   
    try {
    const result = db.query("SELECT id, user_name, password FROM raccoon_user WHERE user_name = ?",[userName]);

    if (!result.length) {
      ctx.response.status = 404; // Not Found
      ctx.response.body = { message: "User not found" };
      return;
    }
    const user=result[0]
    const isValid = verifyPassword(password, user[2]);

    if (!isValid) {
      ctx.response.status = 401; // Unauthorized
      ctx.response.body = { message: "Invalid credentials" };
      return;
    }
    //生成token 
    const token = await generateToken(user[0]);
    ctx.response.status = 200; // OK
    ctx.response.body = { data: { "id": user[0], "userName": user[1],"token":token } };
  } catch (error) {
    console.error("Error during login:", error);
    ctx.response.status = 500;
    ctx.response.body = { message: "Internal server error" };
  }finally {
    closeDB(db);
  }

});

export default authRouter;
